﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Controls;
using Csla.Core;
using System.Collections;
using OpenExpressApp.WPF.Editors;
using System.Windows.Data;
using System.ComponentModel;
using OpenExpressApp.MetaModel;
using Csla;
using System.Reflection;
using OpenExpressApp.Types;
using System.Windows.Input;
using System.Windows;

namespace OpenExpressApp.Module.WPF.Editors
{
    /// <summary>
    /// 表格编辑器
    /// </summary>
    public class GridEditor : ListEditor
    {
        private DataGrid _grid;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="listview">视图对象</param>
        /// <param name="boType">显示的业务模型类型</param>
        public GridEditor(ListObjectView listview, Type boType)
            : base(listview, boType) { }

        /// <summary>
        /// 当前选中的Object
        /// </summary>
        public override object CurrentObject
        {
            get
            {
                return this._grid != null ? this._grid.SelectedItem : null;
            }
            set
            {
                if (this._grid == null)
                {
                    throw new InvalidOperationException("Editor is null");
                }

                //如果value不在数据列表中，则忽略此次设置。
                if (value != null && 
                    this._grid.ItemsSource.OfType<object>().All(o => o != value)
                    )
                {
                    return;
                }

                this._grid.SelectedItem = value;

                //显示此行记录
                if (value != null)
                {
                    try
                    {
                        this._grid.UpdateLayout();
                        this._grid.ScrollIntoView(value);
                    }
                    catch { }
                }
            }
        }

        public override IList SelectedObjects
        {
            get
            {
                return this._grid.SelectedItems;
            }
        }

        public override void NotifyViewDataChanged()
        {
            var viewData = this.View.Data as IEnumerable;
            var collectionView = CollectionViewSource.GetDefaultView(viewData);
            this._grid.GroupStyle.Clear();

            //如果数据量大于400条，则不分组
            if (collectionView != null && viewData != null && viewData.OfType<object>().Count() <= 400)
            {
                string[] groups = ApplicationModel.GetBusinessObjectInfo(this.BOType).GroupDescriptions;
                if (null != groups)
                {
                    foreach (string propertyName in groups)
                    {
                        collectionView.GroupDescriptions.Add(new PropertyGroupDescription(propertyName));

                        GroupStyle gs = new GroupStyle();
                        gs.ContainerStyle = Application.Current.TryFindResource("GroupContainerStyle") as Style;
                        this._grid.GroupStyle.Add(gs);
                    }
                }
            }
            //强制等待更新，执行dg.CurrentItem赋值会空引用错误
            this._grid.UpdateLayout();
            this._grid.ItemsSource = collectionView;

            if (this._grid.Items.Count > 0)
            {
                //设置属性编辑器Visible
                foreach (var col in this._grid.Columns)
                {
                    var column = col as OpenDataGridColumn;

                    if (column != null && column.Editor.IsVisible == false)
                    {
                        col.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        col.Visibility = Visibility.Visible;
                    }
                }
            }

            this._grid.IsReadOnly = this.IsReadOnly;
        }

        public override void SelectAll()
        {
            this._grid.SelectAll();
        }

        /// <summary>
        /// 创建一个DataGrid
        /// </summary>
        /// <returns></returns>
        protected override FrameworkElement CreateControl()
        {
            this._grid = AutoUI.UIFactory.CreateListControl(this.View);

            var listener = this.View as IEventListener;
            if (listener != null)
            {
                //触发View的SelectionChanged和MouseDoubleClick事件
                this._grid.SelectionChanged += delegate(object sender, SelectionChangedEventArgs e)
                {
                    var newItem = e.AddedItems.Count > 0 ? e.AddedItems[0] as BusinessBase : null;
                    var oldItem = e.RemovedItems.Count > 0 ? e.RemovedItems[0] as BusinessBase : null;
                    var args = new SelectedItemChangedEventArgs(newItem, oldItem);
                    listener.NotifySelectedItemChanged(sender, args);
                    e.Handled = true;
                };

                this._grid.MouseDoubleClick += delegate(object sender, MouseButtonEventArgs e)
                {
                    listener.NotifyMouseDoubleClick(sender, e);
                };
            }

            return this._grid;
        }
    }
}
